 //
//  MainTalkAbout.m
//  DataStatistics
//
//  Created by oilklenze on 16/3/16.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "MainTalkAbout.h"
#import "Images.h"
#import "Reply.h"


@implementation MainTalkAbout

+ (MainTalkAbout *)mainTalkAboutWithMessages:(Messages *)messages
                      inManagedObjectContext:(NSManagedObjectContext *)context
{
    MainTalkAbout *mainTalkAbout = nil;
    NSNumber * pk = [[NSNumber alloc]initWithInt:messages.pk];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MainTalkAbout"];
    //谓词
    request.predicate = [NSPredicate predicateWithFormat:@"pk = %@",pk];
    NSError *error;
    //根据谓词查找数据库中的数据 返回一个数值;
    NSArray *matches = [context executeFetchRequest:request error:&error];
    
    if (!matches || error || ([matches count] > 1)) {
        //有错误
    } else if ([matches count]){
        mainTalkAbout = [matches firstObject]; //如果跑到这里实事上也是有错误的，唯一表示不可能有多个存在，要不后台出错，要不数据解析出错;
    } else {
        
        mainTalkAbout = [NSEntityDescription insertNewObjectForEntityForName:@"MainTalkAbout" inManagedObjectContext:context];
    }
    if (mainTalkAbout) {
        mainTalkAbout.pk = pk;
        mainTalkAbout.content = messages.content;
        mainTalkAbout.user_name = messages.user_name;
        mainTalkAbout.deviceNo = messages.deviceNo;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date =[formatter dateFromString:messages.publishTime];
        mainTalkAbout.publishTime =date;
        for (Comments *comment in messages.comments) {
            Reply *reply = [Reply replyWithcomment:comment inManageObjectContext:context];
            [mainTalkAbout addReplyObject:reply];
        }

        for ( NSString *images in  messages.images) {
            Images *imagesURL = [Images imagesWithImageURL:images inManagedObjectContext:context];
            [mainTalkAbout addImagesObject:imagesURL];
        }
    };
    NSLog(@"----->>%@",mainTalkAbout);
    return mainTalkAbout;
    
}


@end
